module PositionCertificateStandardRepository

  def find_certificate_standard position_id, organization_id
    requre_certificate_organs = Organization.find_requre_certificate_organ_by_organ organization_id
    find_certificate_standard_by_position_and_requre_organ position_id, requre_certificate_organs
  end

  def find_certificate_standard_by_position_and_requre_organ position_id, requre_certificate_organs
    PositionCertificateStandard.where(position_id: position_id, requre_certificate_organ: requre_certificate_organs).inject([]) { |mem, var| mem + var.certificates }
  end

  def find_require_organ_by_certificate certificate
    PositionCertificateAssignment.where(certificate: certificate).map { |e| e.position_certificate_standard.requre_certificate_organ }.uniq
  end

  def find_employees_by_certificate certificate, require_organs=nil
    unless require_organs
      require_organs = find_require_organ_by_certificate(certificate).map(&:name)
    end
    employees = EmployeePosition.where(position_id: PositionCertificateAssignment.where(certificate: certificate).map { |e|
      e.position_certificate_standard.position_id
    }).select { |e|
      (require_organs - Organization.find_requre_certificate_organ_by_organ(e.organ_id).map(&:name)).size < require_organs.size
    }.uniq { |s| s.employee_id }

    has_certificate_employees = employees.select {|e|
      !EmployeeCertificate.where(employee_id: e.employee_id, certificate_id: certificate.id).empty?
    }
    {need_certificate_employees: employees, has_certificate_employees: has_certificate_employees}
  end
end